package com.SmartCare.utils;

import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.StandardCharsets;

@Slf4j
public class DataBackupUtil {

  public static void backup(File file, String scriptPath) {
      try {
          // 构建外部脚本命令
          String[] command = { "/bin/bash", scriptPath };

          ProcessBuilder processBuilder = new ProcessBuilder(command);

          // 启动外部脚本
          Process process = processBuilder.start();

          // 处理脚本的输出流和错误流
          InputStream inputStream = process.getInputStream();
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
          OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);

          String str;
          while ((str = bufferedReader.readLine()) != null) {
              outputStreamWriter.write(str + "\r\n");
          }

          outputStreamWriter.flush();
          inputStream.close();
          bufferedReader.close();
          outputStreamWriter.close();
          // 等待脚本执行完毕
          int exitCode = process.waitFor();
          if (exitCode == 0) {
              log.info("数据库备份成功");
          } else {
              log.error("数据库备份失败，退出码：" + exitCode);
          }
      } catch (Exception e) {
          log.error("数据库备份错误,错误信息{}", e.getMessage(), e);
          e.printStackTrace();
      }
  }

}
